<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */

/**
 * Email Service class for communication between controllers and persistent storage
 *
 */
class Core_Service_Email extends RedCross_Service_ServiceAbstract
{
	/**
	 * Constant value to return if one tries to delete an email address
	 * that is the main address of a member
	 * @var string
	 */
	const EMAIL_DELETE_ERROR_IS_MAIN = 'IS_MAIN';

	/**
	 * Constant value to return if one tries to delete an email address
	 * that is the only email address of the member
	 * @var string
	 */
	const EMAIL_DELETE_ERROR_IS_ONLY = 'IS_ONLY';

    /**
     * Constructor
     * @param Core_Gateway_User $gateway
     */
    public function __construct(Core_Gateway_Email $gateway)
    {
        parent::__construct($gateway, 'Core_Model_Email');
    }

    public function getValidator()
    {

    }

    /**
     * Register a new email address with the application
     *
     * @param array $data
     * @return boolean
     */
    public function register(array $data)
    {
        $this->checkAcl('register');
        $model = new Core_Model_Email();
        $model->fromArray($data);
        return $this->save($model);
    }

    /**
     * Deletes an email object from the database
     * Checks if the member that has the email has more than
     * just the one email to be deleted. If not, aborts the deletion
     * @param Core_Model_Email The email model to be deleted
     * @return bool Whether or not the deletion was successful
     */
    public function delete($emailModel)
    {
        $this->checkAcl('delete');
    	if (!is_object($emailModel) || !($emailModel instanceof Core_Model_Email)) {
    		throw new RedCross_Model_Exception("Ugyldig parameter angitt for sletting av epostadresse. Skal v�re en instans av Core_Model_Email");
    	}
    	if ($emailModel->isMain()) {
    		return self::EMAIL_DELETE_ERROR_IS_MAIN;
    	}
    	$member = $emailModel->Member;
    	if (count($member->emails) > 1) //A member must have atleast one email
    	{
    		return parent::delete($emailModel);
    	} else {
    		return self::EMAIL_DELETE_ERROR_IS_ONLY;
    	}
    }

    public function setAsMain(Core_Model_Email $emailModel)
    {
        $this->checkAcl('setAsMain');
    	$memberService = RedCross_Factory::getService('Core_Service_Member');
    	if ($emailModel->isMain())
    	{
    		return true;
    	}
    	$member = $emailModel->Member;
		$memberModel = new Core_Model_Member();
		$memberModel->fromArray($member->toArray());
    	foreach($member->emails as $email)
    	{
    		$email->is_main = 0;
    		$email->save();
    	}
    	$emailModel->is_main = 1;
    	$this->save($emailModel);
    	//$memberService->save($memberModel);
    	return true;
    }
}